package com.basker.pisces.domain.command.meta;

import com.basker.pisces.core.meta.annotation.DataField;
import com.basker.pisces.domain.ISupportEntityBuild;
import com.basker.pisces.domain.constant.DomainConstants;
import com.basker.pisces.domain.entity.meta.Entity;
import com.basker.pisces.domain.property.meta.IdProperty;
import com.basker.pisces.domain.validation.meta.UniquePropertyValidation;

/**
 * 保存命令
 *
 * @author hangwen
 */
public class SaveCommand extends TransactionalCommand implements ISupportEntityBuild {

    @DataField
    private Boolean enableRequiredPropertyValidator = false;

    @DataField
    private Boolean enableStringValueLengthValidator = false;

    @DataField
    private Boolean enableIdPropertyUniqueValidaton = false;

    public SaveCommand() {
        this.setName(SaveCommand.class.getSimpleName());
        this.setRequireFullEntity(true);
    }

    @Override
    public void build(Entity entity) {
        if (this.getEnableIdPropertyUniqueValidaton()) {
            this.addIdPropertyUniqueValidationIfNecessary(entity);
        }
    }

    /**
     * 是否启用IdProperty作为唯一检验，默认false
     *
     * @return
     */
    public Boolean getEnableIdPropertyUniqueValidaton() {
        return enableIdPropertyUniqueValidaton;
    }

    /**
     * 是否启用必填属性校验，默认false
     *
     * @return
     */
    public Boolean getEnableRequiredPropertyValidator() {
        return enableRequiredPropertyValidator;
    }

    /**
     * 是否启用文本属性的最大长度校验,默认false
     *
     * @return
     */
    public Boolean getEnableStringValueLengthValidator() {
        return enableStringValueLengthValidator;
    }

    public void setEnableIdPropertyUniqueValidaton(Boolean enableIdPropertyUniqueValidaton) {
        this.enableIdPropertyUniqueValidaton = enableIdPropertyUniqueValidaton;
    }

    public void setEnableRequiredPropertyValidator(Boolean enableRequiredPropertyValidator) {
        this.enableRequiredPropertyValidator = enableRequiredPropertyValidator;
    }

    public void setEnableStringValueLengthValidator(Boolean enableStringValueLengthValidator) {
        this.enableStringValueLengthValidator = enableStringValueLengthValidator;
    }

    /**
     * 如果实体配置了Id属性，需要添加一个唯一校验
     *
     * @param entity
     */
    private void addIdPropertyUniqueValidationIfNecessary(Entity entity) {
        IdProperty idProperty = entity.getIdProperty();
        if (idProperty != null) {
            UniquePropertyValidation idUniqueValidation = new UniquePropertyValidation(
                    DomainConstants.Validation.ID_UNIQUE_VALIDATION, idProperty.getAlias());

            this.getValidations().add(idUniqueValidation);
        }
    }
}
